# -*- coding: utf-8 -*-
class PurchaseReturnedController < ApplicationController
  before_filter :employee_authorize
  before_filter :sys_before_log
  before_filter :employee_action_hx
  #before_filter :privilege_filter,:except =>[:deliveryConfirm]
  after_filter :sys_after_log

  #显示新添加采购退货订单页面
  def newPurchaseReturned
    
  end

  #显示编辑采购退货订单页面
  def editPurchaseReturned

  end
  
  #显示采购退货订单列表页面
  def purchaseReturnedList
  end

  #显示内勤审批页面
  def associateAuditPurchaseReturned
    
  end

  #显示供仓库使用的采购订单退货列表
  def purchaseReturnedListForDelivery
    
  end
  
  #生成新的采购退货
  def create
    paramsHash = Util.paramsPreprocesseToHash(params[:data])
    #productHash = paramsHash["products"][0]

    purchaseReturned = PurchaseReturned.new
    purchaseReturned.company_id = session[:company_id]
    purchaseReturned.department_id = session[:department_id]
    purchaseReturned.employee_id = session[:employee_id]    
    purchaseReturned.purchase_order_id = paramsHash['purchase_order_id']
    #记录vendorId是为了查询方便。
    purchaseReturned.vendor_id = PurchaseOrder.find(purchaseReturned.purchase_order_id).vendor.id
    purchaseReturned.linkman = paramsHash['linkman']
    purchaseReturned.phone = paramsHash['phone']
    purchaseReturned.delivery_address = paramsHash['delivery_address']
    #purchaseReturned.tax_rate = paramsHash['tax_rate']
    purchaseReturned.return_date = paramsHash['return_date']
    purchaseReturned.description = paramsHash['description']
    purchaseReturned.auditing_status = Constants::AUDIT_APPLY_RETURN
    #插入products信息
    productsHashArray = paramsHash["products"]
    productsHashArray.each do |productHash|
      #只有当用户选择的产品不为空时，才有详细订单。
      if productHash["product_id"] !=""
        purchaseReturnedDetail = PurchaseReturnedDetail.new
        purchaseReturnedDetail.purchase_order_id = paramsHash['purchase_order_id']
        purchaseReturnedDetail.sale_order_id = productHash['sale_order_id']
        purchaseReturnedDetail.product_id = productHash["product_id"]
        purchaseReturnedDetail.quantity = productHash["quantity"]
        purchaseReturnedDetail.unit_price = productHash["unit_price"]
        #purchaseReturnedDetail.discount = productHash["discount"]
        purchaseReturnedDetail.amount = productHash["amount"]
        purchaseReturned.amount = purchaseReturned.amount + purchaseReturnedDetail.amount #计算订单总金额
        purchaseReturnedDetail.description = productHash["description"]
        purchaseReturned.purchase_returned_details << purchaseReturnedDetail
      end
    end
    #purchaseReturned.save

    #开始事务，确保在流水号正常的情况下，保存采购退货订单,一但出现问题，则循环执行
    begin
      Sequence.transaction do
        #开始为采购退货订单取得流水号
        sequence = Sequence.find(:first,:conditions=>["company_id = ? AND sub_type = ?",session[:company_id],PurchaseReturned.name])

        sequence.seq_no = sequence.seq_no + 1
        purchaseReturned.seq_number = sequence.seq_no
        purchaseReturned.order_number = sequence.ab + ":" + purchaseReturned.seq_number.to_s + ":" + Date.today.to_s
        sequence.save!
        purchaseReturned.save!
      end
    rescue ActiveRecord::StaleObjectError
      #这个异常是说明，你当提交时，有人提前更新了你之前读取的信息，违反乐观锁。要retry
      #这里特别指序号产生表。
      logger.info "somebody using sn before yours.............................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"StaleObjectError")
      retry
    rescue ActiveRecord::RecordNotFound
      logger.info "RecordNotFound................................................................................"
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,"RecordNotFound")
    rescue Exception => e
      logger.info "logging......................................................................................."
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
      logger.info e
    end

    info="成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #更新退货采购订单
  def update
    paramsHash = Util.paramsPreprocesseToHash(params[:data])
    
    #productHash = paramsHash["products"][0]
    #这一步的目的是让用户只编辑属于自己的记录
    purchaseReturned = PurchaseReturned.find(:first,:conditions=>["id = ? AND company_id = ? AND is_locked <> 1 AND auditing_status <> ?",paramsHash['id'],session[:company_id],'通过'])
    if purchaseReturned != nil
      purchaseReturned.company_id = session[:company_id]
      purchaseReturned.department_id = session[:department_id]
      purchaseReturned.employee_id = session[:employee_id]
      purchaseReturned.linkman = paramsHash['linkman']
      purchaseReturned.phone = paramsHash['phone']
      purchaseReturned.delivery_address = paramsHash['delivery_address']
      purchaseReturned.return_date = paramsHash['return_date']
      purchaseReturned.description = paramsHash['description']
      purchaseReturned.auditing_status = Constants::AUDIT_APPLY_RETURN

      #products信息
      productsHashArray = paramsHash["products"]
      #在这里，要作一个增，删，编辑操作，以前台数据为准。
      #首先各取出前台与后台的ID数组
      fgIdArray = Array.new
      productsHashArray.each do |productHash|
        fgIdArray << productHash["id"].to_i
      end

      bgIdArray = Array.new
      purchaseReturnedDetails = purchaseReturned.purchase_returned_details
      purchaseReturnedDetails.each do |purchaseReturnedDetail|
        bgIdArray << purchaseReturnedDetail.id
      end

      idIntersectionArray = fgIdArray & bgIdArray
      addIdArray = fgIdArray - idIntersectionArray
      delIdArray = bgIdArray - idIntersectionArray
      PurchaseReturnedDetail.delete(delIdArray)

      #在进行从新整理数据之前，先把销售订单的总金额置“0”
      purchaseReturned.amount = 0

      productsHashArray.each do |productHash|
        #只有当用户选择的产品不为空时，才有详细订单。
        if productHash["product_id"] !=""
          #没Id说明是新增加的。
          if productHash["id"] == ""
            purchaseReturnedDetail = PurchaseReturnedDetail.new
          else
            purchaseReturnedDetail = PurchaseReturnedDetail.find(productHash["id"].to_i)
          end
          purchaseReturnedDetail.product_id = productHash["product_id"]
          purchaseReturnedDetail.quantity = productHash["quantity"]
          purchaseReturnedDetail.unit_price = productHash["unit_price"]
          purchaseReturnedDetail.amount = productHash["amount"]

          purchaseReturned.amount = purchaseReturned.amount + purchaseReturnedDetail.amount #计算订单总金额
          purchaseReturnedDetail.description = productHash["description"]
          purchaseReturned.purchase_returned_details << purchaseReturnedDetail 
        end
      end
      purchaseReturned.save
    end

    info="成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end
  
  #得到所有采购退货订单
  def getAllPurchaseReturneds
    begin
      conditionsHash = Hash.new
      paramsHash = Hash.new
      paramsHash[:offset] = params[:start].to_i
      paramsHash[:limit] = params[:limit].to_i
      conditionsStr = ''

      if params[:order_number].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'seq_number in (:order_number)'
        else
          conditionsStr = conditionsStr+' AND seq_number in (:order_number)'
        end
        conditionsHash[:order_number] = params[:order_number].split(/,/)
      end

      #查询时增加了为仓库，为所有功能，如果为仓库，只查审批完成和撤消二种状态的订单
      searchType = params[:search_type]
      if searchType == "warehouse"
        if conditionsStr == ''
          conditionsStr = "auditing_status != :auditing_status_1 AND auditing_status != :auditing_status_2"
        else
          conditionsStr = conditionsStr+" AND auditing_status != :auditing_status_1 AND auditing_status != :auditing_status_2"
        end
        conditionsHash[:auditing_status_1] = '申请'
        conditionsHash[:auditing_status_2] = '审批退回'
      else
        if params[:auditing_status].to_s != '' && params[:auditing_status] != ' '
          if conditionsStr == ''
            conditionsStr = 'auditing_status like :auditing_status'
          else
            conditionsStr = conditionsStr+' AND auditing_status like :auditing_status'
          end
          conditionsHash[:auditing_status] = '%'+params[:auditing_status].to_s+'%'
        elsif params[:auditing_status] == ' '
          if conditionsStr == ''
            conditionsStr = 'auditing_status = :auditing_status'
          else
            conditionsStr = conditionsStr+' AND auditing_status = :auditing_status'
          end
          conditionsHash[:auditing_status] = ''
        end
      end


      if params[:vendor_id].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'vendor_id = :vendor_id'
        else
          conditionsStr = conditionsStr+' AND vendor_id = :vendor_id'
        end
        conditionsHash[:vendor_id] = params[:vendor_id].to_i
      end

      if params[:begin_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'action_date >= :begin_date'
        else
          conditionsStr = conditionsStr+' AND action_date >= :begin_date'
        end
        conditionsHash[:begin_date] = params[:begin_date].to_date
      end

      if params[:end_date].to_s != ''
        if conditionsStr == ''
          conditionsStr = 'action_date <= :end_date'
        else
          conditionsStr = conditionsStr+' AND action_date <= :end_date'
        end
        conditionsHash[:end_date] = params[:end_date].to_date
      end

      count = PurchaseReturned.countAllPurchaseReturneds conditionsStr,conditionsHash
      purchaseReturneds = PurchaseReturned.findAllPurchaseReturneds conditionsStr,conditionsHash,paramsHash

      jsonStr="{totalProperty:"+count.to_s+",root:"+purchaseReturneds.to_json(:include=>[:employee,:department,:vendor,:associate_auditor,:warehouse_employee,:purchase_order])+"}"
      logger.info jsonStr
      render :text=>jsonStr, :layout=>false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
  end

  #得到采购退货订单的详细信息
  def getPurchaseReturnedDetailsById
    begin
      purchaseReturnedDetails = PurchaseReturnedDetail.find_all_by_purchase_returned_id(params[:purchase_returned_id],:include=>[:product,:sale_order],:order => 'updated_at DESC')
      jsonStr="{totalProperty:"+purchaseReturnedDetails.length.to_s+",root:"+purchaseReturnedDetails.to_json(:include=>[:product,:sale_order])+"}"
      logger.info jsonStr
      render :text=>jsonStr, :layout=>false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
  end

  #内勤审批
  def updateAuditingStatusByAssociate
    purchaseReturned = PurchaseReturned.find(params[:purchase_returned_id])
    info = nil
    if purchaseReturned !=nil
      auditingStatus = params[:auditing_status]
      if(auditingStatus == "是")
        auditingStatus = Constants::PASS_APPLY_RETURN
      else
        auditingStatus = Constants::REJECT_APPLY_RETURN
      end
      purchaseReturned.auditing_status = auditingStatus
      purchaseReturned.associate_auditor_id = session[:employee_id]
      purchaseReturned.associate_audit_opinion =  params[:associate_audit_opinion]
      purchaseReturned.save
      info = "成功"
    else
      info = "失败"
    end
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #采购退货订单出库完毕
  def deliveryFinish
    begin
      purchaseReturned = PurchaseReturned.find(params[:purchase_returned_id])
      if purchaseReturned !=nil
        purchaseReturned.warehouse_employee_id =  session[:employee_id]
        purchaseReturned.warehouse_id =  params[:warehouse_id]
        purchaseReturned.action_date =  params[:action_date]
        purchaseReturned.store_status = Constants::FINISH_DELIVERY

        purchaseReturnedDetails = purchaseReturned.purchase_returned_details
        purchaseReturnedDetails.each do |purchaseReturnedDetail|
          #然后正式拆分此拆分单到结算表中。结算的方式就是主表是负数，然后拆分出来的产品是正数。
          productCollection = ProductCollection.new
          productCollection.company_id = purchaseReturned.company_id
          productCollection.department_id = purchaseReturned.department_id
          productCollection.employee_id = purchaseReturned.employee_id
          productCollection.vendor_id = purchaseReturned.vendor_id
          productCollection.warehouse_id = params[:warehouse_id]
          productCollection.action_date = params[:action_date]
          productCollection.product_id = purchaseReturnedDetail.product_id
          productCollection.quantity = 0 - purchaseReturnedDetail.quantity
          productCollection.description =  purchaseReturnedDetail.description
          productCollection.unit_price = purchaseReturnedDetail.unit_price
          productCollection.unit_amount = 0 - purchaseReturnedDetail.amount
          productCollection.amount = 0 - purchaseReturned.amount
          productCollection.resource_id =  purchaseReturned.id
          productCollection.resource_type =  PurchaseReturned.name
          productCollection.save!
        end
        
        purchaseReturned.save
        #结算表处理完毕。
        info = "成功"
      else
        info = "失败"
      end
      result = "{success:true,info:'#{info}'}"
      render :text=>result, :layout=>false
    rescue Exception => e
      logger.info e
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
  end

  #得到某一个采购退货订单的信息
  def getReturnedPurchaseById
    purchaseReturned = PurchaseReturned.find(params[:id])
    rootStr = purchaseReturned.to_json(:include=>[:vendor,:purchase_order])
    jsonStr = "{root:["+rootStr+"]}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #采购退货订单的撤销
  def applyToCancel
    begin
      purchaseReturned = PurchaseReturned.find(params[:id])
      sysParam =  SysParam.find_by_company_id(session[:company_id])
      if sysParam.audit_for_purchase_returned_cancel == "否"
        purchaseReturned.auditing_status = Constants::PASS_APPLY_CANCEL
        purchaseReturned.deal_with_status = Constants::CANCELED
        ProductCollection.delete_all("resource_type = 'PurchaseReturned' AND resource_id = #{params[:id]}")
        #如果不需要审批，则把汇总表中的数据设置为is_locked = 1
      else
        purchaseReturned.auditing_status = Constants::AUDIT_APPLY_CANCEL
      end
      purchaseReturned.associate_auditor_id = session[:employee_id]
      purchaseReturned.save!
    rescue Exception => e
      info = e.to_s
      logger.info info
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #对于一张销售订单，计算出当前还可以退货的数量和种类
  def getPurchaseOrderDetailsByIdForReturned
    purchaseOrderId = params[:purchase_order_id]
    purchaseOrderDetails = PurchaseOrderDetail.find(:all,:select=>"pd.id,p.id as product_id,p.name as product_name,p.is_suit,pd.unit_price,p.number,p.spec,p.unit,sum(pd.amount) as amount,pd.description,newrd.quantity as rd_quantity,(sum(pd.quantity) - ifnull(newrd.quantity,0)) as balance_quantity",:joins =>"pd
left join (select rd.product_id,sum(rd.quantity) as quantity
from purchase_returned_details rd left join purchase_returneds r on r.id = rd.purchase_returned_id
where r.purchase_order_id = "+purchaseOrderId+" AND r.auditing_status != '#{Constants::PASS_APPLY_CANCEL}'
group by product_id) newrd on newrd.product_id = pd.product_id
left join products p on p.id = pd.product_id
where pd.purchase_order_id =  "+purchaseOrderId+ " group by pd.product_id having sum(pd.quantity) - ifnull(newrd.quantity,0) > 0")

    jsonStr="{totalProperty:"+purchaseOrderDetails.length.to_s+",root:"+purchaseOrderDetails.to_json()+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end
end
